package dao

import (
	"context"
	"gorm.io/gorm"
	"mall_2.0/respository/db/model"
	"mall_2.0/types"
)

type ProductDao struct {
	*gorm.DB
}

func NewProductDao(ctx context.Context) *ProductDao {
	return &ProductDao{
		NewDBClient(ctx),
	}
}

func NewProductDaoByDB(db *gorm.DB) *ProductDao {
	return &ProductDao{db}
}

// CreateProduct 创建商品
func (dao *ProductDao) CreateProduct(product *model.Product) error {
	return dao.DB.Model(&model.Product{}).Create(&product).Error
}

// GetProductByID 通过 ID 获取商品信息
func (dao *ProductDao) GetProductByID(id uint) (product *model.Product, err error) {
	err = dao.DB.Model(&model.Product{}).Where("id = ?", id).First(&product).Error
	return
}

// ListProductByCondition 获取商品列表
func (dao *ProductDao) ListProductByCondition(condition map[string]interface{}, page types.BasePage) (products []*model.Product, err error) {
	err = dao.DB.Model(&model.Product{}).Where(condition).Offset((page.PageNum - 1) * page.PageSize).Limit(page.PageSize).Find(&products).Error
	return
}

// CountProductByCondition 获取商品数量
func (dao *ProductDao) CountProductByCondition(condition map[string]interface{}) (count int64, err error) {
	err = dao.DB.Model(&model.Product{}).Where(condition).Count(&count).Error
	return
}

// UpdateProduct 更新商品
func (dao *ProductDao) UpdateProduct(pID uint, product *model.Product) error {
	return dao.DB.Model(&model.Product{}).Where("id = ?", pID).Updates(&product).Error
}

// DeleteProduct 删除商品
func (dao *ProductDao) DeleteProduct(pID, uID uint) error {
	return dao.DB.Model(&model.Product{}).Where("id = ? AND boss_id = ?", pID, uID).Delete(&model.Product{}).Error
}

// SearchProduct 搜索商品
func (dao *ProductDao) SearchProduct(info string, page types.BasePage) (products []*model.Product, count int64, err error) {
	err = dao.DB.Model(&model.Product{}).Where("name LIKE ? OR info LIKE ?", "%"+info+"%", "%"+info+"%").Offset((page.PageNum - 1) * page.PageSize).Limit(page.PageSize).Find(&products).Error
	if err != nil {
		return
	}
	err = dao.DB.Model(&model.Product{}).Where("name LIKE ? OR info LIKE ?", "%"+info+"%", "%"+info+"%").Count(&count).Error
	return
}
